// pages/invoice/list/list.js
import Dialog from "../../../miniprogram_npm/@vant/weapp/dialog/dialog";
import api from "../../../utils/api";
import util from '../../../utils/util';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    coId: '',
    activeTab: 0,// 发票申请0 发票作废1
    active: 0,
    tabList: ['全部', '未提交', '进行中', '已通过', '已拒绝', '已作废', '已超期'],
    fpzftabList: ['全部', '未提交', '进行中', '已通过', '已拒绝'],
    fpzflistData: [],

    secondTab1: 0,
    searchValue: '', //搜索框内容
    getList: [], //全部

    nodata: false, //是否没有数据
    tips: '暂无数据',
    loading: true,
    remind: '下拉加载更多',
    page: 0, // 当前页码
    pageSize: 10, // 每页显示数据
    currentPage: 1, // 当前页码--发票作废列表
    leftdel: false,
    noleftdel: true, //左滑删除

    totalInvMoney: '', //总金额
    total: '', //总发票数量

    shijianShow: false,
    bumenShow: false,
    shenpijiedianShow: false,
    add: true, //+号 显示隐藏
    value1: '',
    value2: '',
    value3: '',
    value4:'',
    filtertype: '',
    clickdID: '', //选中的项
    dateList: [{
        id: 0,
        name: '全部时间'
      },
      {
        id: 1,
        name: '本月'
      },
      {
        id: 2,
        name: '本周'
      },
      {
        id: 3,
        name: '今日'
      }
    ],
    startDate: '', //开始时间
    endDate: '', //结束时间
    date: '',
    showCalendar: false,
    getLeixingList:[], //类型list
    leixingName:'',//选中的 类型 筛选项
    getApprovalNodeList: [], //审批节点list
    shenpijieidanName:'',//选中的  审批节点 筛选项
    getDeptList: [], //部门list
    bumenName:'',// 选中的 部门 筛选项
    shijianName:'',//选中的 时间 筛选项
    today:[],
  },
  //关闭筛选的时候 add 显示
  OnClose(){
    this.setData({
      add: true
  })
  },
  //类型筛选
  leixingOpen(){
    let that = this;
   
    api.getBusinessTypeList({
      data: {
        coId: this.data.coId,
        // word: this.data.receiveType,
      },
      success: function (res) {
        console.log(res.data.data, "类别")
        if (res.data.code == 200) {
          if (res.data.data.length > 0) {
            that.setData({
              getLeixingList:res.data.data
           })
          } 
        }
      }
    })
  },

  clickLeixingItem(e){
    console.log(e,e.currentTarget.dataset.filtertype)
    this.setData({
      leixingName: e.currentTarget.dataset.filtertype,
    })
  },
  //类型筛选--取消
  leixingCenle() {
    this.selectComponent('#search4').toggle();
    this.setData({
        value4: '',
        leixingName: '',
        add: true
    })
    this.clearData()
  },
  //类型筛选--确认
  leixingOk(){
    this.selectComponent('#search4').toggle();
    console.log(this.data.leixingName)
    if( this.data.leixingName){
        console.log('不为空')
        this.setData({
          leixingName:  this.data.leixingName,
          value4 : this.data.leixingName,
          add: true
      })
       this.clearData()
    } 
  },
  //审批节点筛选
  shenpijiedianOpen() {
    let that = this;
    that.setData({
      add: false
    })
    that.getApprovalNodeList()
  },
  clickshenpijiedianItem(e){
    console.log(e,e.currentTarget.dataset.filtertype)
    this.setData({
      shenpijieidanName: e.currentTarget.dataset.filtertype,
    })
  },
  //审批节点 -- 取消
  shenpijiedianCenle(){
    this.selectComponent('#search3').toggle();
    this.setData({
        value3: '',
        shenpijieidanName: '',
        add: true
    })
    this.clearData()
  },
  //审批节点 -- 确认
  shenpijiedianOk(){
    this.selectComponent('#search3').toggle();
    console.log(this.data.shenpijieidanName)
    if(this.data.shenpijieidanName){
        this.setData({
          shenpijieidanName : this.data.shenpijieidanName,
          value3 : this.data.shenpijieidanName,
          add: true
      })
       this.clearData()
    } 
  },
  //部门筛选
  bumenOpen() {
    let that = this;
    that.setData({
      add: false 
    })
    that.getDeptList()
  },
  clickbumenItem(e){
    console.log(e,e.currentTarget.dataset.filtertype)
    this.setData({
      bumenName: e.currentTarget.dataset.filtertype,
    })
  },
  //部门筛选 -- 取消
  bumenCenle(){
    this.selectComponent('#search2').toggle();
    this.setData({
        value2: '',
        bumenName: '',
        add: true
    })
    this.clearData()
  },
  //部门筛选 -- 确认
  bumenOk(){
    this.selectComponent('#search2').toggle();
    console.log(this.data.bumenName)
    if(this.data.bumenName){
        this.setData({
          bumenName : this.data.bumenName,
          value2 : this.data.bumenName,
          add: true
      })
       this.clearData()
    } 
  },
  //时间筛选
  shijianOpen(e){
    console.log(e,'vvvv')
    let that = this;
    that.setData({
      add: false 
    })
  },
  clickshijianItem(e){
    this.setData({
      shijianName: e.currentTarget.dataset.filtertype,
      //选月周日时 把自定义时间置空
      customStartDate:'',
      customEndDate:'',
    })
    console.log(e,e.currentTarget.dataset.filtertype)
    if(e.currentTarget.dataset.filtertype == '全部时间'){
      this.data.startDate = '',
      this.data.endDate = ''
    }else if(e.currentTarget.dataset.filtertype == '本月'){
      this.data.startDate = this.formatDate(new Date(new Date().getFullYear(), new Date().getMonth(), 1)),
      this.data.endDate = this.formatDate(new Date())
      console.log(this.data.startDate,this.data.endDate,'--------月')
    }else if(e.currentTarget.dataset.filtertype == '本周'){
      this.data.startDate = this.formatDate(new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate() - new Date().getDay() + 1)),
      this.data.endDate = this.formatDate(new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate() - new Date().getDay() + 7))
      console.log(this.data.startDate,this.data.endDate,'--------周')
    }else if(e.currentTarget.dataset.filtertype == '今日'){
      console.log(this.formatDate(new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate())))
      this.data.startDate = this.formatDate(new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate())),
      this.data.endDate = this.formatDate(new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate()))
      console.log(this.data.startDate,this.data.endDate,'-------日')
    } else {
      this.setData({
        startDate: this.data.startDate,
        endDate: this.data.endDate
      })
    }
  },
  shijianCenle(){
    this.selectComponent('#search1').toggle();
    this.setData({
        value1: '',
        startDate: '',
        endDate: '',
        add: true
    })
    this.clearData()
  },
  shijianOk(){
    this.selectComponent('#search1').toggle();
    console.log(this.data.shijianName,this.data.startDate,this.data.endDate)
    if( this.data.startDate && this.data.endDate ){
        this.setData({
          startDate: this.data.startDate,
          endDate: this.data.endDate,
          value1 : this.data.shijianName ?  this.data.shijianName : this.data.startDate +'~'+ this.data.endDate,
          add: true
      })
       this.clearData()
    } else{
      console.log('全部时间')
      this.clearData()
    }
  },
  //开始时间-结束时间
  onDisplay() {
    let todayStart = new Date().getTime() - (1000 * 60 * 60 * 24 * 1) //前一天的时间
    let todayEnd = new Date().getTime()  //前一天的时间
    let today = [todayStart,todayEnd]
    this.setData({
      today: today,
      date: new Date().getTime(),
      minDate: new Date(new Date().getFullYear()-2, 0, 1).getTime(),
      maxDate: new Date(new Date().getFullYear()+3, -1, 31).getTime(),
      showCalendar: true
    });
  },
  onClose() {
    this.setData({
      showCalendar: false
    });
  },
  formatDate(date) {
    date = new Date(date);
    let month = date.getMonth() + 1
    let day = date.getDate()
    if (month < 10) {
      month = '0' + month
    }
    if (day < 10) {
      day = '0' + day
    }
    return `${date.getFullYear()}-${month}-${day}`;
  },
  onConfirm(event) {
    const [start, end] = event.detail;
    this.setData({
      showCalendar: false,
      //自定义时间时 把时间筛选项 置空
      shijianName:'',
      customStartDate: this.formatDate(start),
      customEndDate: this.formatDate(end)
    });
    if(this.data.customStartDate && this.data.customEndDate){
      this.setData({
        // value1 : this.data.customStartDate+'~'+this.data.customEndDate,
        startDate: this.data.customStartDate,
        endDate: this.data.customEndDate,
      })
    }
    console.log('自定义时间',this.data.customStartDate,this.data.customEndDate)
  },
  //部门筛选列表
  getDeptList() {
    let that = this;
    api.getDeptList({
      success: function (res) {
        console.log(res.data.data, "getDeptList")
        if (res.data.code == 200) {
          that.setData({
            getDeptList: res.data.data,
            // clickdID:res.data.data[0].id
          })
        }
      }
    })
  },
  //审批节点筛选列表
  getApprovalNodeList() {
    let that = this;
    api.getApprovalNodeList({
      success: function (res) {
        console.log(res.data.data, "getApprovalNodeList")
        if (res.data.code == 200) {
          that.setData({
            getApprovalNodeList: res.data.data,
          })
        }
      }
    })
  },

  //tab切换 发票申请0 发票作废1
  onChangetabfp(event){
    console.log(event, "发票申请0 发票作废1")
    this.setData({
      activeTab:event.detail.name
    })
    if(event.detail.name == 1){
      //原发票作废页面中的 发票作废列表
      this.clearfpzfData()
    }
    if(event.detail.name == 0){
      this.clearData()
    }
  },
  clearfpzfData(){
    this.setData({
      fpzflistData: [],
      currentPage: 1,
      loading: true,
      nodata: false,
      tips: '暂无数据'
    })
    this.getfpzfListData()
  },
  //获取发票作废列表
  getfpzfListData(){
    let that = this;
    api.getListByType({
      data: {
        searchStr: that.data.searchValue ? that.data.searchValue : '',
        pageNum: that.data.currentPage,
        pageSize: that.data.pageSize,
        tabStr: that.data.secondTab1
      },
      success: function (res) {
        console.log('发票作废！！！！！！！！！！！！！！')
        if (res.data.code == 200) {
          if (res.data.data.list.length > 0) {
            that.data.ZFtotalPage = res.data.data.totalPage;
            for(let i=0;i<res.data.data.list.length;i++){
              res.data.data.list[i].money = util.formatFigure(res.data.data.list[i].money)
            }
            that.setData({
              fpzflistData: that.data.fpzflistData.concat(res.data.data.list),
              loading: false,
              nodata: false,
              remind: res.data.data.totalPage > res.data.data.pageNum ? '下拉加载更多' : '已经到底啦～'
            })
          } else {
            that.setData({
              nodata: true
            })
          }
        }
      }
    })
  },
  //发票作废列表tab切换
  secondChange1(event) {
    console.log(event,'发票作废列表tab切换')
    this.setData({
      secondTab1: event.detail.index,
    })
    this.clearfpzfData()
  },

  //搜索
  onSearch(event) {
    console.log(event.detail.value, "pppp")
    this.setData({
      searchValue: event.detail && event.detail.value ? event.detail.value : event.detail,
      loading: true,
    })
    this.clearData()
  },
  // 切换tab
  tabsChange(event) {
    console.log(event, "pppp")
    if (event.detail.name == 1) {
      this.setData({
        noleftdel: false,
        leftdel: true
      })
    } else {
      this.setData({
        noleftdel: true,
        leftdel: false
      })
    }
    this.setData({
      active: event.detail.name,
      //切换时筛选条件值为空
      value1: '',
      value2: '',
      value3: '',
      filtertype: '',
      clickdID: '',
      startDate: '',
      endDate: ''
    })
    this.clearData()
  },
  //获取全部列表
  getList() {
    console.log(this.data.bumenName, '部门')
    console.log(this.data.shenpijieidanName, '审批节点')
    console.log(this.data.startDate, '开始时间')
    console.log(this.data.endDate, '结束时间')
    let that = this;
    that.setData({
      page: this.data.page + 1
    })
    api.invList({
      data: {
        coId: this.data.coId,
        tabStr: this.data.active,
        searchStr: that.data.searchValue ? that.data.searchValue : '',
        pageNum: this.data.page,
        pageSize: that.data.pageSize,
        // filterType: this.data.filtertype ? this.data.filtertype : '',
        // filterStr: this.data.clickdID ? this.data.clickdID : '',
        deptName: this.data.bumenName ? this.data.bumenName : '',
        nodeStr: this.data.shenpijieidanName ? this.data.shenpijieidanName : '',
        startTimeStr: this.data.startDate ? this.data.startDate : '',
        endTimeStr: this.data.endDate ? this.data.endDate : '',
        businessTypeStr: this.data.leixingName ? this.data.leixingName : ''
      },
      success: function (res) {
        console.log(res.data.data.list, "getList")
        if (res.data.code == 200) {
          if (res.data.data.list.length > 0) {
            for (let i = 0; i < res.data.data.list.length; i++) {
              res.data.data.list[i].money = that.addComma(res.data.data.list[i].money)
            }
            that.data.totalPage = res.data.data.totalPage
            that.setData({
              getList: that.data.getList.concat(res.data.data.list),
              loading: false,
              nodata: false,
              remind: res.data.data.totalPage > res.data.data.pageNum ? '下拉加载更多' : '已经到底啦～',
              total: res.data.data.total,
              totalInvMoney: that.addComma (res.data.data.totalInvMoney)
            })
          } else {
            that.setData({
              nodata: true
            })
          }
        }
      }
    })
  },
  //清空数据并重新加载数据
  clearData() {
    this.setData({
      getList: [],
      loading: true,
      page: 0,
      loading: true,
      nodata: false,
      tips: '暂无数据'
    })
    this.getList()
  },
  //点击新建
  clickadd() {
    wx.removeStorageSync('receTerm')
    wx.removeStorageSync('receTerm2')
    wx.removeStorageSync('bankType')
    wx.removeStorageSync('bankTypeStr')
    wx.removeStorageSync('date')
    wx.removeStorageSync('receTermCode') 
    wx.navigateTo({
      url: '/pages/addNewinvoice/addNewinvoice',
    })
  },

  //删除list
  delList(e) {
    let index = e.currentTarget.dataset.index;
    let that = this
    Dialog.confirm({
        message: '确定删除吗？',
      })
      .then(() => {
        api.delInv({
          data: {
            id: e.currentTarget.dataset.id
          },
          success: function (res) {
            if (res.data.code == 200) {
              that.data.getList.splice(index, 1)
              that.setData({
                getList: that.data.getList
              })
              wx.showToast({
                title: '删除成功',
                icon: 'success'
              })
            }
          }
        })
      })
      .catch(() => {
        // on cancel
        console.log('取消操作')
      });
  },
  //千分位 转换
  addComma(date) {
    let str = '';
    let num = '';
    let newStr = '';
    date = date + '';
    if (date.indexOf('.') != -1) {
      num = date.split('.')[0]
      str = date.split('.')[1]
    } else {
      num = date
    }
    newStr = num.toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,');
    newStr = str == '' ? newStr : newStr + '.' + str;
    return newStr;
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {},

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    console.log('showwwwwww')
    this.data.coId = wx.getStorageSync('userInfo').coId
    // this.getList()
    this.clearData()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if(this.data.activeTab == 0){
      if (this.data.totalPage > this.data.page) {
      // ++this.data.page;
      this.setData({
        loading: true
      })
      this.getList()
    }
    }
    if(this.data.activeTab == 1){
      if(this.data.ZFtotalPage > this.data.currentPage){
      ++this.data.currentPage;
      this.setData({
        loading: true
      })
      this.getfpzfListData()
    }
    }
    
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
    /**
   * 获取滚动条当前位置
   */
  onPageScroll:function(e){ // 获取滚动条当前位置
    // console.log(e,'获取滚动条当前位置')
    // console.log(e.scrollTop)//获取滚动条当前位置的值
},
   /**
   *  一键回到顶部
   */
goTop: function (e) {  
  if (wx.pageScrollTo) {//判断这个方法是否可用
     wx.pageScrollTo({
       scrollTop: 0
     })
   } else {
     wx.showModal({
       title: '提示',
       content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
     })
   }
 }
})